<script setup lang="ts">
import type { RenderContent } from '@arco-design/web-vue/es/_utils/types'
import type { CertAccountListItem } from '@/apis/model/cert'
import { Message } from '@arco-design/web-vue'
import { deleteCertAcmeApi, getCertAcmeListApi } from '@/apis/modules/cert'
import { commonTableProps } from '@/utils/table'
import EditorDialog from './dialogs/EditorDialog.vue'
import useConfig from './useConfig'

const { tableColumns } = useConfig()

const queryParams = ref({ email_keyword: '' })

const {
  loading,
  data: tableData,
  run,
} = useListRequest(getCertAcmeListApi, {
  params: queryParams,
  immediate: true,
})

const {
  visible: editorDialogVisible,
  open: openEditorDialog,
  data: editorDialogData,
} = usePopup()

// 删除
function handleDelete(record: CertAccountListItem) {
  ModalHelper.error({
    title: '删除 ACME 账户',
    content: h('div', null, [
      '确定要删除 “',
      h('span', { class: 'text-[#FA5566]' }, `${record.email || '-'}`),
      '” ACME 账户吗？',
    ]) as unknown as RenderContent,
    okText: '删除',
    width: 480,
    closable: false,
    onOk: async () => {
      await deleteCertAcmeApi({ id: record.id })
      await run()
      Message.success('删除成功')
    },
  })
}

const { createSortChange } = useTable(run, tableData)
const onSorterChange = createSortChange(queryParams)
</script>

<template>
  <main-container
    :pagination="false"
    :loading="loading"
    @run="run"
  >
    <template #header>
      <div class="flex space-x-4">
        <a-button
          type="primary"
          @click="openEditorDialog()"
        >
          新建 ACME 账户
        </a-button>
        <a-input-search
          v-model="queryParams.email_keyword"
          placeholder="默认按照账户邮箱搜索"
          class="!w-58"
          allow-clear
          @clear="run()"
          @search="run()"
        />
      </div>
    </template>

    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="tableData"
      @sorter-change="onSorterChange"
    >
      <template #actions="{ record }">
        <a-link
          :hoverable="false"
          :disabled="record.node_count > 0"
          status="danger"
          @click="handleDelete(record)"
        >
          <i-icons-delete size="16px" />
        </a-link>
      </template>
    </a-table>
  </main-container>

  <editor-dialog
    v-model:visible="editorDialogVisible"
    :record="editorDialogData"
    @reload="run"
  />
</template>

<style scoped></style>
